package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.Column;
import com.ruoyi.system.service.ColumnService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/publish/column")
public class ColumnController extends BaseController {
    @Autowired
    private ColumnService columnService;
    /**
     * 查询栏目信息列表*/

//    方法执行前的权限验证
    @PreAuthorize("@ss.hasPermi('publish:column:list')")
    @GetMapping("list")
    public TableDataInfo list(Column column) {
        List<Column> list = columnService.selectColumnList(column);
        return getDataTable(list);
    }
   //获取子栏目列表
   @PreAuthorize("@ss.hasPermi('system:column:item')")
    @GetMapping("/childList/{columnId}")

    public AjaxResult childList(@PathVariable("columnId") Long columnId) {
        List<Column> list = columnService.selectChildColumnsByParentId(columnId);
      list.removeIf(c -> c.getColumnId().intValue() ==columnId || ArrayUtils.contains(StringUtils.
              split(c.getAncestors(), ","), columnId + ""));
       return success(list);
    }

    //添加栏目或子栏目
    @PreAuthorize("@ss.hasPermi('publish:column:add')")
    @Log(title = "栏目管理", businessType = BusinessType.INSERT)
    @Anonymous
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Column column) {
        if (!columnService.checkColumnNameUnique(column)) {
            return error("新增栏目'" + column.getColumnName() + "'失败，栏目名称已存在");
        }
        column.setCreateBy(getUsername());
        return toAjax(columnService.insertColumn(column));
    }
    // 编辑栏目
    @PreAuthorize("@ss.hasPermi('publish:column:edit')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Column column) {
        if (!columnService.checkColumnNameUnique(column)) {
            return error("修改栏目'" + column.getColumnName() + "'失败，栏目名称已存在");
        }
        column.setUpdateBy(getUsername());
        return toAjax(columnService.updateColumn(column));
    }
    // 删除栏目
    @PreAuthorize("@ss.hasPermi('publish:column:remove')")
    @Log(title = "栏目管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{columnId}")
    public AjaxResult remove(@PathVariable Long columnId) {
        try {
            // 调用级联删除方法
            int result = columnService.deleteColumnCascade(columnId);
            return toAjax(result > 0); // 根据实际返回值调整
        } catch (Exception e) {
            // 捕获自定义异常，返回友好提示
            return AjaxResult.error(e.getMessage());
        }
    }
    // 显示栏目
    @PreAuthorize("@ss.hasPermi('publish:column:show')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PutMapping("/show/{columnId}")
    public AjaxResult show(@PathVariable Long columnId) {
        Column column = columnService.selectColumnById(columnId);
        if (column == null) {
            return error("栏目不存在");
        }
        column.setVisible("0"); // 假设状态0为显示
        column.setUpdateBy(getUsername());
        // 如果是父栏目，显示所有子栏目
        if (column.getParentId() == null || column.getParentId()==0) {
            columnService.showChildColumns(columnId);
        }
        return toAjax(columnService.updateColumn(column));
    }
    // 隐藏栏目
    @PreAuthorize("@ss.hasPermi('publish:column:hide')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PutMapping("/hide/{columnId}")
    public AjaxResult hide(@PathVariable Long columnId) {
        Column column = columnService.selectColumnById(columnId);
        if (column == null) {
            return error("栏目不存在");
        }
        // 判断是否为一级栏目（parentId为null或0）
        if (column.getParentId() == null || column.getParentId() == 0) {
            // 检查是否有未隐藏的子栏目
            if (columnService.hasUnHiddenChildren(columnId)) {
                return error("存在未隐藏的子栏目，请先隐藏所有子栏目");
            }
        }
        // 执行隐藏操作
        column.setVisible("1");
        column.setUpdateBy(getUsername());
        return toAjax(columnService.updateColumn(column));

    }
}
